package com.yang.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * Created by ygs on 2017/7/10.
 */
@Component
@Aspect
@EnableAspectJAutoProxy
public class TomPointAdvice {

    @Pointcut(value="execution(* com.yang.service..*.*(..))")
    private  void  anyValue(){

    }
    @Before(value = "anyValue()")
    public  void  beforeAdvice(JoinPoint joinPoint) {

        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        try{
            Class targetClass = Class.forName(targetName);
            Method[] methods = targetClass.getMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Parameter[] parameters = method.getParameters();
                    if (parameters.length == arguments.length) {
                        Tom[] toms = method.getAnnotationsByType(Tom.class);
                        for(Parameter para : parameters){
                            System.out.println("实际参数为： "+para.getName());
                            for (Tom tom : toms) {
                                System.out.println("注解的参数为： "+tom.name()[0]);

                                if(tom.name().equals("hello")){
                                    throw  new RuntimeException ("参数错误！");
                                }

                            }
                        }

                    }
                    break;
                }
            }

        }catch (ClassNotFoundException e){

        }

        /*for (int i = 0; i < joinPoint.getArgs().length; i++) {
            System.out.println("参数:  "+joinPoint.getArgs()[i]);
        }*/
        System.out.println("执行到before置通知"+joinPoint.getTarget().getClass().getName());

    }/*
    @After(value = "anyValue()")
    public  void  afterAdvice(JoinPoint joinPoint){

        System.out.println("执行到after后置置通知"+joinPoint.getArgs().toString());

    }
    @Around(value = "anyValue()")
    public  void  aroundAdvice(JoinPoint joinPoint){

        System.out.println("执行到around置通知"+joinPoint.getArgs().toString());

    }*/

}
